const Base = require('./base.js');

module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);
		this.goods = this.model('store/goods');
		this.specification = this.model('store/specification');
		this.product = this.model('store/product');
		this.goods_specification = this.model('store/goods_specification');
		this.goods_attribute = this.model('store/goods_attribute');
		this.goods_issue = this.model('store/goods_issue');
		this.goods_gallery = this.model('store/goods_gallery');

	}
	async indexAction() {
		if(this.isGet) {
			return this.display();
		}

		let posts = this.post();

		let where = {};
		if(!think.isEmpty(posts.userid)) {
			where.user_id = posts.userid;
		}
		const data = await this.goods.dataTable(posts, where, "goods_desc");
		console.log(JSON.stringify(data))
		return this.json(data);
	}

	async addAction() {
		if(this.isGet) {
			let specification = await this.specification.select();
			this.assign("specification", specification);

			return this.display();

		}

		let posts = this.post();

		try {
			await this.goods.startTrans();
			let db = this.goods.db();
			let goods_id = await this.goods.add({
				name: posts.name,
				goods_sn: posts.goods_sn,
				market_price: posts.market_price,
				retail_price: posts.retail_price,
				goods_unit: posts.goods_unit,
				category_id: posts.category_id,
				brand_id: posts.brand_id,
				primary_pic_url: posts.primary_pic_url,
				list_pic_url: posts.list_pic_url,
				digest: posts.digest,
				keywords: posts.keywords,
				type_id: posts.type,
				content: posts.content,
				goods_number: posts.goods_number,
				is_hot: posts.is_hot ? 1 : 0,
				is_new: posts.is_new ? 1 : 0,
				is_on_sale: posts.is_on_sale ? 1 : 0,
				create_time: new Date().valueOf()
			});

			let attribute = JSON.parse(posts.attribute);
			if(!think.isEmpty(attribute)) {
				for(let i in attribute) {
					attribute[i].goods_id = goods_id;
				}
				await this.goods_attribute.db(db).addMany(attribute);
			}

			let specification = JSON.parse(posts.specification);
			if(!think.isEmpty(specification)) {
				for(let i in specification) {
					specification[i].goods_id = goods_id;
				}
				await this.goods_specification.db(db).addMany(specification);

				let product = JSON.parse(posts.product);

				let specification_ids = await this.goods_specification.db(db).where({
					goods_id: goods_id
				}).select();

				if(!think.isEmpty(product)) {
					for(let i in product) {
						product[i].goods_id = goods_id;
						let goods_specification_ids = [];
						let specvalue = product[i].specification_value;
						for(let x in specvalue) {
							let specification_id = "";
							for(let y in specification_ids) {
								if(specification_ids[y].specification_id == specvalue[x].id && specification_ids[y].value == specvalue[x].value) {
									specification_id = specification_ids[y].id;
								}
							}
							if(specification_id) {
								goods_specification_ids.push(specification_id);
							}

						}
						product[i].goods_specification_ids = goods_specification_ids.join("_");
						product[i].goods_sn = posts.goods_sn + "-"+goods_specification_ids.join("-");
					}
					await this.product.db(db).addMany(product);
				}

			}
			else {
				await this.product.db(db).add({
					goods_id: goods_id,
					goods_sn: posts.goods_sn,
					goods_specification_ids: '',
					retail_price: posts.retail_price,
					goods_number: posts.goods_number,
					pic_url: posts.primary_pic_url
				});
			}

			await this.goods.commit();
			return this.success("添加成功");
		}
		catch(e) {
			console.log(e)
			await this.goods.rollback();
			return this.fail("添加失败，请重试");
		}

	}

	async detailAction() {
		if(this.isGet) {
			let gets = this.get();
			let goods = await this.goods.findOne(gets.id);
			let specification = {};
			goods.specification.forEach((a) => {
				specification[a.id] = a.value;
			});
			
			this.assign("specification", specification);
			this.assign("goods", goods);
			return this.display();
		}

	}

	async deleteAction() {
		let ids = this.post("id") || JSON.parse(this.post("ids"));
		console.log(ids);
		try {
			await this.goods.startTrans();
			let db = this.goods.db();
			await this.goods.where({
				id: ['IN', ids]
			}).setRelation(false).delete();
			await this.goods_attribute.db(db).where({
				goods_id: ['IN', ids]
			}).delete();
			await this.goods_specification.db(db).where({
				goods_id: ['IN', ids]
			}).delete();

			await this.product.db(db).where({
				goods_id: ['IN', ids]
			}).delete();

			await this.goods.commit();
			return this.success("删除成功");

		}
		catch(e) {
			console.log(e)
			await this.goods.rollback();
			return this.fail("删除失败，请重试");
		}

	}

	async editAction() {
		if(this.isGet) {
			let gets = this.get();
			let specificationArr = await this.specification.select();
			let goods = await this.goods.findOne(gets.id);
			let specification = {};
			goods.specification.forEach((a) => {
				specification[a.id] = a.value;
			});

			let product = [];

			for(let p of goods.product) {

				let ids = await this.goods_specification.where({ id: ['IN', p.goods_specification_ids.split("_")] }).select();

				p.specification_value = [];
				for(let i = 0; i < ids.length; i++) {
					p.specification_value.push({
						id: ids[i].specification_id,
						value: ids[i].value
					});
				}

				if(ids[0]) {
					product.push(p);
				}

			}
			console.log(product)

			goods.product = product;
			
			this.assign("specification", specification);
			this.assign("specificationArr", specificationArr);
			this.assign("goods", goods);
			return this.display();
		}

		let posts = this.post();
		console.log(posts);

		try {
			await this.goods.startTrans();
			let db = this.goods.db();
			let goods_id = posts.id;
			await this.goods.setOne(posts.id, {
				name: posts.name,
				goods_sn: posts.goods_sn,
				market_price: posts.market_price,
				retail_price: posts.retail_price,
				goods_unit: posts.goods_unit,
				category_id: posts.category_id,
				brand_id: posts.brand_id,
				primary_pic_url: posts.primary_pic_url,
				list_pic_url: posts.list_pic_url,
				digest: posts.digest,
				keywords: posts.keywords,
				type_id: posts.type,
				content: posts.content,
				goods_number: posts.goods_number,
				is_hot: posts.is_hot ? 1 : 0,
				is_new: posts.is_new ? 1 : 0,
				is_on_sale: posts.is_on_sale ? 1 : 0
			});

			let attribute = JSON.parse(posts.attribute);

			if(!think.isEmpty(attribute)) {
				let attrUpdate = [];
				let attrAdd = [];
				let attrUpdateIds = [];

				for(let i in attribute) {
					attribute[i].goods_id = goods_id;
					if(attribute[i].id) {
						attrUpdate.push(attribute[i]);
						attrUpdateIds.push(attribute[i].id);
					} else {
						attrAdd.push(attribute[i]);
					}

				}

				await this.goods_attribute.db(db).where({
					goods_id: goods_id,
					id: ['NOTIN', attrUpdateIds]
				}).delete();

				if(!think.isEmpty(attrUpdate)) {
					await this.goods_attribute.db(db).updateMany(attrUpdate);
				}

				if(!think.isEmpty(attrAdd)) {
					await this.goods_attribute.db(db).addMany(attrAdd);
				}

			} else {
				await this.goods_attribute.db(db).where({
					goods_id: goods_id
				}).delete();
			}

			let specification = JSON.parse(posts.specification);
			if(!think.isEmpty(specification)) {

				let specUpdate = [];
				let specAdd = [];
				let specUpdateIds = [];
				for(let i in specification) {
					specification[i].goods_id = goods_id;
					if(specification[i].id) {
						specUpdate.push(specification[i]);
						specUpdateIds.push(specification[i].id);
					} else {
						specAdd.push(specification[i]);
					}
				}

				await this.goods_specification.db(db).where({
					goods_id: goods_id,
					id: ['NOTIN', specUpdateIds]
				}).delete();

				if(!think.isEmpty(specUpdate)) {
					await this.goods_specification.db(db).updateMany(specUpdate);
				}

				if(!think.isEmpty(specAdd)) {
					await this.goods_specification.db(db).addMany(specAdd);
				}

				let product = JSON.parse(posts.product);

				let specification_ids = await this.goods_specification.db(db).where({
					goods_id: goods_id
				}).select();

				if(!think.isEmpty(product)) {
					let proUpdate = [];
					let proAdd = [];
					let proUpdateIds = [];
					for(let i in product) {
						product[i].goods_id = goods_id;
						let goods_specification_ids = [];
						let specvalue = product[i].specification_value;
						for(let x in specvalue) {
							let specification_id = "";
							for(let y in specification_ids) {
								if(specification_ids[y].specification_id == specvalue[x].id && specification_ids[y].value == specvalue[x].value) {
									specification_id = specification_ids[y].id;
								}
							}
							if(specification_id) {
								goods_specification_ids.push(specification_id);
							}

						}
						product[i].goods_specification_ids = goods_specification_ids.join("_");
						
						product[i].goods_sn = posts.goods_sn + "-"+goods_specification_ids.join("-");

						if(product[i].id) {
							proUpdate.push(product[i]);
							proUpdateIds.push(product[i].id);
						} else {
							proAdd.push(product[i]);
						}

					}

					await this.product.db(db).where({
						goods_id: goods_id,
						id: ['NOTIN', proUpdateIds]
					}).delete();

					if(!think.isEmpty(proUpdate)) {
						await this.product.db(db).updateMany(proUpdate);
					}

					if(!think.isEmpty(proAdd)) {
						await this.product.db(db).addMany(proAdd);
					}

				} else {
					await this.product.db(db).where({
						goods_id: goods_id
					}).delete();
				}

			}
			else {
				await this.goods_specification.db(db).where({
					goods_id: goods_id
				}).delete();

				let product = await this.product.db(db).where({
					goods_id: goods_id
				}).select();
				if(product.length == 1 && !product[0].goods_specification_ids) {
					await this.product.db(db).setOne(product[0].id, {
						goods_id: goods_id,
						goods_sn: posts.goods_sn,
						goods_specification_ids: '',
						retail_price: posts.retail_price,
						goods_number: posts.goods_number,
						pic_url: posts.primary_pic_url
					});
				} else {
					await this.product.db(db).where({
						goods_id: goods_id
					}).delete();

					await this.product.db(db).add({
						goods_id: goods_id,
						goods_sn: posts.goods_sn,
						goods_specification_ids: '',
						retail_price: posts.retail_price,
						goods_number: posts.goods_number,
						pic_url: posts.primary_pic_url
					});

				}

			}

			await this.goods.commit();
			return this.success("修改成功");
		}
		catch(e) {
			console.log(e)
			await this.goods.rollback();
			return this.fail("修改失败，请重试");
		}

	}

};